package tt.dz.biz.service.task;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import tt.dz.biz.annotation.MsLog;
import tt.dz.biz.dao.common.CommonDAO;
import tt.dz.biz.dao.merch.ChangeDayDAOImp;
import tt.dz.biz.service.Job.JobLockService;
import tt.dz.common.BusinessException;
import tt.dz.common.DateUtil;
import tt.dz.common.DzConstants;
import tt.dz.common.DzConstants.BizType;
import tt.dz.common.DzConstants.SysState;
import tt.dz.common.DzConstants.bizSysCode;
import tt.dz.common.DzConstants.jobStatus;
import tt.dz.common.DzConstants.sysJob;
import tt.dz.common.LogUtil;
import tt.dz.vo.ChangeDayVO;
import tt.dz.vo.JobLockVO;

@Service("changeDayTask")
public class ChangeDayTaskService
  extends DailyTaskService
{
  @Resource(name="changeDayDAO")
  ChangeDayDAOImp changeDayDAO;
  @Resource(name="commonDAO")
  CommonDAO commonDAO;
  @Resource(name="jobLockService")
  protected JobLockService jobLockService;
  
  @MsLog(bizCode="changeDayTask", bizName="日切任务", bizType=DzConstants.BizType.JOB, bizDesc="此任务包含日切和账户昨日余额计算")
  public void execute()
    throws Exception
  {
    try
    {
      beforeExecuteTask();
      
      LogUtil.info("日切任务执行开始");
      ChangeDayVO changeDayVo = this.changeDayDAO.queryChangeDay();
      Assert.notNull(changeDayVo, "查询日切对象为空，请检查！");
      Date tmrAccountingDate = changeDayVo.getTmrAccountingDate();
      Calendar tmrAccountingCalendar = Calendar.getInstance();
      tmrAccountingCalendar.setTime(tmrAccountingDate);
      tmrAccountingCalendar.set(5, tmrAccountingCalendar.get(5) + 1);
      changeDayVo.setYtdAccountingDate(changeDayVo.getAccountingDate());
      changeDayVo.setAccountingDate(changeDayVo.getTmrAccountingDate());
      changeDayVo.setTmrAccountingDate(tmrAccountingCalendar.getTime());
      changeDayVo.setUpdatedDate(DateUtil.getDBCurrentTime());
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      LogUtil.debug("日切昨天：" + df.format(changeDayVo.getAccountingDate()));
      LogUtil.debug("日切账务日期：" + df.format(changeDayVo.getTmrAccountingDate()));
      LogUtil.debug("日切明天：" + df.format(tmrAccountingCalendar.getTime()));
      LogUtil.debug("日切表VO：" + changeDayVo);
      this.changeDayDAO.updteSubjectAccLastBal();
      Date now = this.commonDAO.getDBCurrentTime();
      if (now != null) {
        changeDayVo.setUpdatedDate(now);
      }
      this.changeDayDAO.updateChangeDay(changeDayVo);
      
      afterExecuteTask();
      
      LogUtil.info("日切任务执行完成");
    }
    catch (Exception e)
    {
      LogUtil.error("日期任务异常，jobvo为：" + this.jobvo, e);
      throw e;
    }
  }
  
  protected void beforeExecuteTask()
    throws Exception
  {
    this.jobvo = this.jobLockService.updateJobStatusForLock(DzConstants.sysJob.CHANGE_DAY_TASK.value());
    if (null == this.jobvo) {
      throw new BusinessException("锁日切任务（" + DzConstants.sysJob.CHANGE_DAY_TASK.value() + "）失败，不能执行！！！");
    }
    String stateCode = this.commonDAO.getCurrentSysState(DzConstants.bizSysCode.MAIN_SERVER.value());
    if (!this.jobvo.getStateCode().equals(stateCode)) {
      throw new BusinessException("系统状态为" + stateCode + "与运行日切任务需要的状态" + DzConstants.SysState.NORMAL_RUNNING.value() + "不一致，不能执行日切任务。");
    }
  }
  
  protected void afterExecuteTask()
    throws Exception
  {
    this.jobvo.setStatus(DzConstants.jobStatus.WAITING.value());
    this.jobLockService.updateJobStatusForRestart(this.jobvo);
    try
    {
      this.jobLockService.updateLastRunTimeByCode(this.jobvo.getJobCode());
      int i = this.commonDAO.updateSysCurrentState(DzConstants.SysState.DAY_CHANGED.value());
      if (i < 1) {
        throw new Exception("日切任务（changeDayTask）后更新系统当前状态失败！");
      }
    }
    catch (Exception e)
    {
      LogUtil.error("日切任务完成处理异常，jobcode为：" + this.jobvo.getJobCode(), e);
      throw e;
    }
  }
}
